package cn.dreambug.messageQ;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQObjectMessage;

import cn.dreambug.pojo.MoneyMessage;

public class Recv {

	private static MessageConsumer consumer;

	/**
	 * recvFlag = 0(暂停状态) recvFlag = 1(正常处理) recvFlag = 2(停止处理)
	 */
	private static int recvFlag = 0;

	/**
	 * 保证messageRecv具有全局唯一性(增强安全性)
	 */
	private static boolean onlyFlag = false;

	public static void messageOnlyRecv(MessageConsumer consumer) {
		if (onlyFlag == false) {
			onlyFlag = true;
		} else {
			System.err
					.println("请勿连续调用(Recv.public static void messageOnlyRecv(MessageConsumer consumer) 方法) - 本次调用无效！");
			return;
		}

		if (onlyFlag) {
			while (true) {
				if (recvFlag == 0) {
					continue;
				} else if (recvFlag == 2) {
					break;
				}
				try {
					ActiveMQObjectMessage msg;
					msg = (ActiveMQObjectMessage) consumer.receive(100000);
					if (msg != null) {
						MoneyMessage s = (MoneyMessage) msg.getObject();
						System.out.println("toString：\n" + s.toString());
					}
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 开始/继续-处理
	 */
	public static void startRecv() {
		recvFlag = 1;
	}

	/**
	 * 暂停-处理
	 */
	public static void suspendRecv() {
		recvFlag = 0;
	}

	/**
	 * 停止-处理
	 */
	public static void stopRecv() {
		recvFlag = 2;
	}

	/**
	 * 开始队列消息处理
	 */
	public static void messageRecvInit() {
		consumer = null;
		ConnectionFactory connectionFactory;
		Connection connection = null;
		Session session;
		Destination destination;

		connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");
		try {
			connection = connectionFactory.createConnection();
			connection.start();
			session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
			destination = session.createQueue("wechat - message");
			consumer = session.createConsumer(destination);
			new Thread(new Runnable() {
				public void run() {
					System.out.println("GOGOGOGO Running...!");
					Recv.startRecv();
					Recv.messageOnlyRecv(consumer);
				}
			}).start();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	public static MessageConsumer getConsumer() {
		return consumer;
	}
}
